import {Component, OnDestroy, OnInit} from '@angular/core';
import {ResponseUtil} from '../../../util/response-util';
import {PageSubject} from '../../../util/page-subject';
import {TableUtil} from '../../../util/table-util';
import {DaAirfactorService} from './da-airfactor.service';
import {DaAPI} from '../da-constants';
import {MsgConstants} from '../../../constants/constants';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {MsgSubscribeService, SubscribeConstants} from '../../../tools/msgSubscribe/msg-subscribe.service';
import {RabbitConfig} from '../../../app.config';

declare var $;
declare var moment;

@Component({
  selector: 'app-da-airfactor',
  templateUrl: './da-airfactor.component.html',
  styleUrls: ['./da-airfactor.component.css']
})
export class DaAirfactorComponent implements OnInit, OnDestroy {
// 数据格式
  timeDataType = 'hourData';
  timeDataArr: Array<any> = [];
  // 日期选择
  startDate = new Date(moment().subtract(1, 'w').format('YYYY/MM/DD HH:00'));
  endDate =  new Date();
  // 站点
  siteCode = '';
  rangeCode = '';
  // 多选
  factorDataArr: Array<any> = [];
  factorDataObj: any = {};

  table: any;
  tableData: Array<any> = [];

  siteArr: Array<any> = [];

  isInitTable = true;
  isLoading = true;
  /**
   * 禁用日期数组
   * @type {any[]}
   */
  disabledDate: Array<any> = [];

  private subConstants: SubscribeConstants;
  tempHumData: any = {};
  constructor(
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private dialogService: OneDialogService,
    private airFactorService: DaAirfactorService,
    private subscribeService: MsgSubscribeService,
    private tableUtil: TableUtil
  ) {
    this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    this.initData();
    this.getSiteData();
  }
  ngOnDestroy () {
    this.subscribeService.unsubscribe();
  }
  /**
   * 面包屑导航
   */
  pushPage() {
    // const path = new Path('多因子分析', '');
    this.pageSubject.pushPage('空气六因子数据', '查询');
  }
  /**
   * 实例化对象
   */
  initObject() {
    this.subConstants = new SubscribeConstants();
  }
  /**
   * 初始化数据
   */
  initData() {
    this.timeDataArr = [{name: '小时', dataType: 'hourData'}, { name: '日', dataType: 'dayData'}];
    this.tableData = [];
  }
  /**
   * 时间类型切换
   * @param timeDataType
   */
  timeDataChange(timeDataType) {
    if (this.timeDataType === timeDataType) {
      return false;
    }
    if (this.timeDataType !== timeDataType && !this.factorDataObj.hasOwnProperty(timeDataType)) {
      this.timeDataType = timeDataType;
      this.changeStartAndEndDate();
      this.getTableHeadData();
    } else {
      this.timeDataType = timeDataType;
      this.factorDataArr = this.factorDataObj[timeDataType];
      this.changeStartAndEndDate();
      this.search();
      // this.table.bootstrapTable('selectPage', 1);
    }
    // this.search();
  }

  /**
   * 日期选择
   */
  startValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.startDate = null;
    //   this.dialogService.info('开始时间大于结束时间')
    // }
  };
  endValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.endDate = null;
    //   this.dialogService.info('结束时间小于开始时间')
    // }
  };
  disabledStartDate = (startValue) => {
    if (!startValue || !this.endDate) {
      return false;
    }
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= startValue.getTime()  && startValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime() || !isInRange;
    } else {
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime();
    }
  };
  disabledEndDate = (endValue) => {
    if (!endValue || !this.startDate) {
      return false;
    }
    const startDateTime =  new Date(moment(this.startDate).format('YYYY/MM/DD')).getTime();
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= endValue.getTime()  && endValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime || !isInRange;
    } else {
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime;
    }
  };
  get showTimeParams() {
    if (this.timeDataType === 'hourData') {
      return {
        nzFormat: 'HH'
      }
    } else {
      return false;

    }
  }
  /**
   * addColumns
   * @returns {any[]}
   */
  addColumns = () => {
    const colArr = [
      // {field: 'regionName', title: '城市', valign: 'middle', align: 'center'},
      // {field: 'siteName', title: '站点名称', valign: 'middle', align: 'center'},
      // {field: 'monitorTime', title: '时间', valign: 'middle', align: 'center'},
      // {field: 'PM10', title: 'PM<sub>10</sub>', align: 'right'},
      // {field: 'PM2_5', title: 'PM<sub>2.5</sub>', align: 'right'},
      // {field: 'SO2', title: 'SO<sub>2</sub>', align: 'right'},
    ];
    this.factorDataArr.forEach((val) => {
        if (val.flag) {
          colArr.push({field: val.code, title: val.name, align: 'right'});
        } else {
          colArr.push({field: val.code, title: val.name, valign: 'middle', align: 'center'});
        }
    });
    // if (this.timeDataType === 'hourData') {
    //   colArr.push(
    //     {field: 'NO', title: 'NO', align: 'right'},
    //     {field: 'NO2', title: 'NO<sub>2</sub>', align: 'right'},
    //     {field: 'NOx', title: 'NO<sub>x</sub>', align: 'right'},
    //     {field: 'CO', title: 'CO', align: 'right'},
    //     {field: 'O3', title: 'O<sub>3</sub>', align: 'right'}
    //   );
    // } else if (this.timeDataType === 'dayData') {
    //   colArr.push(
    //     {field: 'NO2', title: 'NO<sub>2</sub>', align: 'right'},
    //     {field: 'CO', title: 'CO', align: 'right'},
    //     {field: 'O3', title: 'O<sub>3</sub>', align: 'right'},
    //     {field: 'O3_8h', title: 'O<sub>3</sub>-8h', align: 'right'}
    //   )
    // }
    return colArr
  };
  loadAirFactor() {
    this.table = this.tableUtil.load('one_table_airfactor',  {
      columns: this.addColumns(),
      idField: 'id',
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: '上一页',
      paginationNextText: '下一页',
      singleSelect: false, // 多选
      clickToSelect: true, // 点击选中
      toolbar: '#one_operation_airfactor',
      data: this.tableData,
      url: DaAPI.airFactorPageList,
      method: 'get',
      // //传递附加参数
      queryParams: (params) => {
        params.siteCode = this.siteCode;
        params.dataType = this.timeDataType;
        params.tableDataType =  'tableData';
        let format = 'YYYY-MM-DD HH:00:00';
        if (this.timeDataType === 'dayData') {
          format = 'YYYY-MM-DD 00:00:00'
        }
        params.startTime = this.startDate ? moment(this.startDate).format(format) : '';
        params.endTime = this.endDate ? moment(this.endDate).format(format) : '';
        // params.pageNum = params.offset ? (params.offset / params.limit) + 1 : 1;
        // params.pageCount = params.limit;
        return params;
      },
      // //返回数据处理器
      responseHandler: (result) => {
        this.isLoading = false;
        return this.responseUtil.bsPageHandler(result, () => {
        });
      },
      height: 700, // table高度
      sortable: true,
      order: 'asc',
      classes: 'table table-hover',
      striped: true, // 隔行变色
      paginationLoop: false, // 是否开启循环分页
      mobileResponsive: true // 响应式
    });
  }

  /**
   * 搜索
   */
  search () {
    if (this.startDate > this.endDate) {
      this.dialogService.info('开始时间大于结束时间，请重新选择');
    } else {
      this.isLoading = true;
      this.tableUtil.refreshOptions({columns: this.addColumns(), pageNumber: 1});
    }
  }

  /**
   * 导出
   */
  exportExcel = () => {
    let format = 'YYYY-MM-DD HH:00:00';
    if (this.timeDataType === 'dayData') {
      format = 'YYYY-MM-DD 00:00:00'
    }
    const params = {
      siteCode: this.siteCode,
      dataType: this.timeDataType,
      limit: 10000,
      startTime: this.startDate ? moment(this.startDate).format(format) : '',
      endTime: this.endDate ? moment(this.endDate).format(format) : '',
    };
    this.airFactorService.getExcel(params).subscribe(
      result => this.processExport(result),
      error => this.responseUtil.error(error)
    )
  };
  processExport(result) {
    const blob = new Blob([result]);
    const reader = new FileReader();
    reader.readAsText(blob, 'utf-8');
    reader.onload = (e) => {
      if (reader.result) {
        if (reader.result.indexOf('code') !== -1) {
          const resultObj = JSON.parse(reader.result);
          if (!this.responseUtil.preSuccess(resultObj)) {
            this.dialogService.info(resultObj.message)
          }
        } else {
          let timeType = '';
          this.timeDataArr.every((val) => {
            if (val.dataType === this.timeDataType) {
              timeType = val.name;
              return false;
            } else {
              return true;
            }
          });
          const filename = '空气六因子' + '_' + (this.startDate ? moment(this.startDate).format('YYYYMMDDHH') : '')
            + '_'
            + (this.endDate ? moment(this.endDate).format('YYYYMMDDHH') : '')
            + '_'
            + timeType + '数据'
            + '_' + new Date().getTime()
            + '.xlsx';
          this.saveAs(blob, filename);
        }
      }
    }
  };
  /**
   * 保存
   * @param  {Blob} blob
   * @param  {String} filename 想要保存的文件名称
   */
  saveAs = (blob, filename) => {

    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, filename);
    } else {
      const link = document.createElement('a');
      const body = document.querySelector('body');

      link.href = window.URL.createObjectURL(blob);
      link.download = filename;

      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);

      link.click();
      body.removeChild(link);

      window.URL.revokeObjectURL(link.href);
    }
  };
  /**
   * 获取站点数据
   */
  getSiteData = () => {
    this.airFactorService.getSiteData().subscribe(
      result => this.responseUtil.success(result, this.progressD),
      error => this.responseUtil.error(error)
    )
  };
  progressD = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.siteArr = result.data;
        this.siteCode = this.siteArr[0].SITECODE;
        this.rangeCode = this.siteArr[0].RANGECODE;
        this.changeSite(false);
        this.subscribeHump();
      }
      this.getTableHeadData();
    } else {
      this.dialogService.info(result.message);
    }
  };
  changeSite = (isOpen) => {
    if (!isOpen) {
      if (this.rangeCode) {
        this.disabledDate = [];
        let site;
        this.siteArr.every((val) => {
          if (val.RANGECODE === this.rangeCode) {
            if (this.siteCode !== val.SITECODE) {
              this.subscribeService.unsubscribe();
              this.tempHumData = {};
              this.subscribeHump();
            }
            this.siteCode = val.SITECODE;
            site = val;
            return false
          } else {
            return true
          }
        });
        if (site.DATESTR && typeof site.DATESTR === 'string' ) {
          const dateArr = site.DATESTR.split(';');
          if (dateArr.length > 0) {
            dateArr.forEach((val) => {
              const singleDateArr = val.split(',');
              this.disabledDate.push({startDate: singleDateArr[0], endDate: singleDateArr[1]})
            });
            this.changeStartAndEndDate();
          }
        }
      } else {
        this.disabledDate = [];
        this.siteCode = '';
      }
    }
  };
  /**
   * 修改开始结束时间
   */
  changeStartAndEndDate = () => {
    if (this.disabledDate.length > 0) {
      const dateLength = this.disabledDate.length;
      const dateObj = this.disabledDate[dateLength - 1];
      const startTime = new Date(moment(dateObj.startDate).format('YYYY/MM/DD 00:00:00'));
      const endTime = new Date(moment(dateObj.endDate).format('YYYY/MM/DD 00:00:00'));
      const nowDate =  new Date(moment().format('YYYY/MM/DD 00:00:00'));
      const nowDateIsInRange = startTime.getTime() < nowDate.getTime()  && nowDate.getTime() <= endTime.getTime();
      if (nowDateIsInRange) {
        this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        let startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          startDate = new Date(moment().subtract('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          startDate = new Date(moment().subtract('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          startDate = new Date(moment().subtract('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        const startDateIsInRange = startTime.getTime() < startDate.getTime()  && startDate.getTime() < endTime.getTime();
        if (startDateIsInRange) {
          this.startDate = startDate;
        } else {
          this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        }
      } else {
        this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        let endDate = new Date(moment(dateObj.endDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        if (endDate.getTime() > new Date().getTime()) {
          this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        } else {
          this.endDate = endDate;
        }
      }
    }
  };
  /**
   * 获取表格数据
   */
  getTableHeadData = () => {
    const dataObj = {
      limit: 1,
      order: 'asc',
      offset: 0,
      tableDataType: 'tableHead',
      siteCode: this.siteCode,
      dataType: this.timeDataType,
      startTime: this.startDate ? moment(this.startDate).format('YYYY-MM-DD HH:00:00') : '',
      endTime: this.endDate ? moment(this.endDate).format('YYYY-MM-DD HH:00:00') : ''
    };
    this.airFactorService.getTableHeadData(dataObj).subscribe(
      result => this.responseUtil.success(result, this.handleHeadData),
      error => this.responseUtil.error(error)
    )
  };
  handleHeadData = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.nameList && result.data.nameList.length > 0) {
        this.factorDataArr = result.data.nameList;
        this.factorDataObj[this.timeDataType] = result.data.nameList
      }
      if (this.isInitTable) {
        this.loadAirFactor();
      } else {
        this.search();
      }
      this.isInitTable = false;
    } else {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 订阅机柜温湿度实时数据
   */
  subscribeHump = () => {
    this.subConstants.url = '/exchange/analysis/analysisData.' + this.siteCode;
    this.subConstants.callback = this.receiveData;
    this.subscribeService.subscribe(this.subConstants)
  };
  /**
   * 接收到数据
   */
  receiveData = (message) => {
    this.tempHumData = JSON.parse(message.body);
    this.tempHumData.temperature = parseFloat(this.tempHumData.temperature);
    this.tempHumData.humidity = parseFloat(this.tempHumData.humidity);
  }
}
